package com.saret.crawler.type;

import com.saret.utils.UtfFileHandle;

import java.io.File;
import java.util.*;

/**
 * User: biniam.gebremichael
 * Date: 2/3/11
 */
public class GWordList {

    Map<String, GWord> gWordMap = new HashMap<String, GWord>();
    //   Map<GWord, Long> gWordMap = new TreeMap<GWord, Long>();


    public GWordList() {
    }

    public GWordList(File wordListFile) {
        List<String> lines = UtfFileHandle.readFileToListOfLines(wordListFile);
        for (String s : lines) {
            String[] line = s.split("\\s+", 2);
            GWordImpl gWord = new GWordImpl(line[1], Long.valueOf(line[0]));
            gWordMap.put(line[1], gWord);
        }

    }

    public void put(GWord gWord) {
        if (gWordMap.containsKey(gWord.getWord())) {
            long oldOcc = gWordMap.get(gWord.getWord()).getOccurrence();
            gWordMap.remove(gWord.getWord());
            gWord.increment(oldOcc);
        }
        gWordMap.put(gWord.getWord(), gWord);
    }

    public void put(Collection<GWord> gWords) {
        for (GWord gWord : gWords) {
            put(gWord);
        }

    }

    public Collection<GWord> getgWordMap() {
        return gWordMap.values();
    }

    public Collection<GWord> getSortedGWord() {
        SortedSet<GWord> sorted = new TreeSet<GWord>();
        Iterator<GWord> iterator = getgWordMap().iterator();
        while (iterator.hasNext()) {
            sorted.add(iterator.next());
            iterator.remove();
        }
        return sorted;
    }


}
